<script setup>
  import { ref } from 'vue'

  import { storeToRefs } from 'pinia'

  import FormFlatLayout from '@/layouts/FormFlatLayout.vue'
  import { useProjectConfigStore, useProjectStore } from '@/stores/project'
  import ProjectForm from './ProjectForm.vue'

  // props attendu par le composant
  const props = defineProps({
    edit: { type: Boolean, default: false },
    projectId: { type: Number || null, default: null },
    url: { type: String, required: true },
    formConfigUrl: { type: String, required: true },
    layout: { type: Object, default: FormFlatLayout },
  })

  const emit = defineEmits(['saved', 'cancel'])

  const isEdit = !!props.projectId
  const loading = ref(true)

  const formConfigStore = useProjectConfigStore()
  formConfigStore.setUrl(props.formConfigUrl)
  const projectStore = useProjectStore()

  const preload = async () => {
    const promises = [formConfigStore.loadConfig()]

    if (isEdit) {
      projectStore.setCurrentProjectId(props.projectId)
      promises.push(projectStore.loadProject())
    }
    Promise.all(promises).then(() => (loading.value = false))
  }
  const { item: project } = storeToRefs(projectStore)

  function onSaved(project) {
    emit('saved', project)
  }
  function onCancel() {
    console.log('Cancel Project add/edit')
    emit('cancel')
  }
  await preload()
</script>
<template>
  <div v-if="loading">Chargement des informations</div>
  <ProjectForm
    v-else
    :project="project"
    :layout="layout"
    @saved="onSaved"
    @cancel="onCancel"
  />
</template>
